package com.wangxiaobao.charge.mylibrary.engine;

import com.wangxiaobao.charge.mylibrary.engine.adapter.DataAdapter;
import com.wangxiaobao.charge.mylibrary.request.RequestData;
import com.wangxiaobao.charge.mylibrary.response.ResponseData;
import com.wangxiaobao.charge.mylibrary.utils.HexUtil;
import com.wangxiaobao.charge.mylibrary.utils.LogUtil;
import me.jahnen.libaums.core.driver.scsi.ScsiBlockDevice;

public abstract class AbsScsi {
    private ScsiBlockDevice scsiBlockDevice;

    public AbsScsi(ScsiBlockDevice scsiBlockDevice) {
        this.scsiBlockDevice = scsiBlockDevice;
    }

    protected <T> T send(RequestData req, DataAdapter<T> adapter) throws Exception{
        byte[] reqBytes = req.getByteData();
         LogUtil.log("发送数据:"+ HexUtil.printBuffer(reqBytes));
         byte[] result=scsiBlockDevice.writeCom(reqBytes);
        LogUtil.log("收到数据:"+ HexUtil.printBuffer(result));
         //截取数据
        // h  c  err len   data
        // ef 01 00 11 5758425930333032313132303430303234 2020202020202020202020
        ResponseData responseData=ResponseData.fromValue(result);
        LogUtil.log("截取后真实数据:"+responseData);
        int errorCode=responseData.getErrorCode();
        if(errorCode!=0){
            LogUtil.log("请求失败,错误码:"+ErrorCode.of(errorCode));
            throw new Exception(ErrorCode.of(errorCode).getMessage());
        }else{
            Object obj=adapter.parse(responseData.getData());
            //f8940c2d ble  2d0c94f8  e846de62 62de46e8
            //         scsi 2d0c916c
            return (T) obj;
        }
     }
}
